<?php

//session_start(); // prepare use of session variables

$prev_uri = $_SESSION['prev_uri']; // URI of previous page

$con = mysqli_connect ( "localhost", "cms", "cms", "cms" );
if (mysqli_connect_errno ()) { // Check connection
	echo "Failed to connect to MySQL: " . mysqli_connect_error ();
}

if ($_SERVER ['REQUEST_METHOD'] === 'POST') {
	
	$pid = $_POST[id];
	$title = $_POST[title];
	$content = $_POST[content];
	$topmenu = $_POST[topmenu];
	
	if ($pid) { // editing existing page
		$sql = "UPDATE page SET title = '$title', content='$content', topmenu='$topmenu' WHERE id='$pid'";
	} else {
		$sql = "INSERT INTO page (title, content,topmenu) VALUES ('$title','$content','$topmenu')";
	}
	if (! mysqli_query ( $con, $sql )) {
		die ( 'Error: ' . mysqli_error ( $con ) );
	}
	echo "Page saved";
} else {
	$pid = $_GET[id];
	$sql = "SELECT title,content,topmenu FROM page WHERE id = '$pid'";
	$result = mysqli_query ( $con, $sql );
	$row = mysqli_fetch_array ( $result );
	$title = $row[title];
	$content = $row[content];
	$topmenu = $row[topmenu];
}

mysqli_close ( $con );

?>

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="../main.css">
<title>Edit page - <?php echo $title; ?></title>
</head>
<body>
<div class="topbar" >
	<a href="<?php if ($prev_uri) echo $prev_uri; else echo '../'; ?>">Go to site</a>
</div>

<div class="admincontent">
	<div class="admintopmenu">
		<?php include("menu.php")?>
	</div>
	<div><h2>Edit page</h2></div>

	<form action="edit_page.php" method="post">
		<input hidden="true" name="id" value="<?php echo $pid; ?>" />
		<div>
			Title:
		</div>
		<div>
			<input type="text" name="title" value="<?php echo $title; ?>" />
		</div>
		<div>
			Content:
		</div>
		<div>
			<textarea rows="10" cols="100" name="content"><?php echo $content; ?></textarea>
		</div>
		<div>
			Topmenu <input type="checkbox" name="topmenu" <?php if ($topmenu) echo "checked=\"checked\""; ?> />
		</div>
		<div>
			Left menu <input type="checkbox" name="leftmenu" />
		</div>
		<div>
			Right menu <input type="checkbox" name="rightmenu" />
		</div>
		<div>
			<input type="submit" value="Save">
		</div>
	</form>
	</div>
</body>
</html>
